/**
 * 
 */
package ca.utoronto.cms.cscc85.project4.teamrf;

import ca.utoronto.cms.cscc85.project4.teamrf.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
 * This class adds recipes to the database
 *
 */
public class AddRecipeActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private EditText RecipeNameText;
	private EditText IngredientText;
	private EditText TimeText;
	private Button addRecipeButton;
	private EditText DirectionText;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addrecipe);
                 
        //Initialize all text boxes
        RecipeNameText = (EditText) findViewById(R.id.recipeName);
        IngredientText = (EditText) findViewById(R.id.Ingredient);
        DirectionText = (EditText) findViewById(R.id.DirectionText);
        TimeText = (EditText) findViewById(R.id.TimeField);
        
        //Initialize the add recipe button
        addRecipeButton = (Button) findViewById(R.id.AddRecipeButton);
        
        //set initial text for recipe fields
        addRecipeButton.setOnClickListener(this);
        
    }
    
    /**
     * Once the add recipe button is clicked, it will submit it to the database 
     */
    public void onClick(View v) {
    			
		String holdrName = "";
		String holdIngredient = "";
		String holdDirections = "";
		Integer holdTimeText = 0;
		if(v == addRecipeButton) {
			holdrName = RecipeNameText.getText().toString().toLowerCase();
			holdIngredient = IngredientText.getText().toString().toLowerCase();
			holdTimeText = parsetime(TimeText.getText().toString());
			holdDirections = DirectionText.getText().toString().toLowerCase();
			
			//parse all input
			if(parse(holdrName, holdIngredient, holdDirections, holdTimeText)){
				//select the largest id and makes a new unique id
				String getIDSQL = "SELECT _id FROM recipes ORDER BY _ID DESC LIMIT 1";
				Cursor results = Main.getDatabase().rawQuery(getIDSQL, null);
				results.moveToNext();				
				Integer ids = results.getInt(0) + 1;
				results.close();
				
				//insert new entry
				String query = "INSERT INTO recipes VALUES(" + Integer.toString(ids) + ", '" + 
		                holdrName + "','" + holdIngredient + "','" + holdDirections + "'," 
		                + TimeText.getText().toString() + ")";
				
				Main.getDatabase().execSQL(query);
				MessageBox("Your recipe has been added.");
				
				//go back to main page
				Intent addIntent = new Intent(this, Main.class);
				startActivity(addIntent);
			}
			
		}
			
	}
	
	/**
	 * Parses the input fields to make sure they are all filled
	 * @param holdrName
	 * @param holdIngredient
	 * @param holdDirectionText
	 * @param holdTimeText
	 * @return boolean
	 */
	private boolean parse(String holdrName, String holdIngredient,
			String holdDirectionText, Integer holdTimeText) {
		boolean correctlyFormated = false;
		
		if(correctRecipeName(holdrName) && correctIngredient(holdIngredient) &&
		   correctDirections(holdDirectionText) && correctTime(holdTimeText)){
			return true;			
		}
		return correctlyFormated;
	}
	
	/**
	 * Make sure directions are formated correctly
	 * @param holdDirectionText
	 * @return
	 */
	private boolean correctDirections(String holdDirectionText) {
		if(holdDirectionText.length() < 1){			
			MessageBox("Please enter in your recipe's Directions");
		}else if(containdigit(holdDirectionText)){
			return true;
		}else{
			MessageBox("Please number your steps in your directions.");			
		}
		return false;
	}
	
	/**
	 * Makes sure that the time is correctly formated
	 * @param holdTimeText
	 * @return
	 */
	private boolean correctTime(Integer holdTimeText) {
		if ((holdTimeText > 0) && (holdTimeText< 24)){
		return true;			
		}else{
			MessageBox("Please enter in the correct time needed.");
			
		}
		return false;
	}
	
	/**
	 * Confirms that you have correctly formated ingredients 
	 * @param holdIngredient
	 * @return boolean
	 */
	private boolean correctIngredient(String holdIngredient) {
		 		
		if(holdIngredient.length() < 1){			
			MessageBox("Please enter in your recipe's Ingredients");
		}else if(containdigit(holdIngredient )){
			return true;
		}else{
			MessageBox("Please specify how many of each ingredient you have.");
			
		}
		return false;
	}
	
	/**
	 * Sees if digits are in the string
	 * @param holdIngredient
	 * @return
	 */
	private boolean containdigit(String holdIngredient) {
		boolean isnum = false;
		
		for(int i = 0; i < holdIngredient.length();i++){
			
			if(Character.isDigit(holdIngredient.charAt(i))){
				isnum = true;
			}
			
		}
		return isnum;
	}


	/**
	 * Confirms that a correctly formated recipe name was given
	 * @param holdrName
	 * @return boolean
	 */
	private boolean correctRecipeName(String holdrName) {
		char symbols[] = {'.', '&', '^', '@', '#', '$', '%',
				'/', '\'','|','(',')','-','_','+','=','*','`','~',
				':',',',';','?','>','<','"','[',']','{','}'};
		CharSequence seq = new String(symbols);
		if (holdrName.length() < 1) {			
			MessageBox("Please enter in your recipe's Name");
		} else if (!holdrName.contains(seq )) {
			return true;
		} else {
			MessageBox("The recipe Name cannot contain symbols please.");
		}
		return false;
	}

	/**
	 * This function creates an alert box with hte message given.
	 * @param message
	 */
	public void MessageBox(String message){
		AlertDialog ad = new AlertDialog.Builder(this).create();
		ad.setCancelable(false);
		ad.setMessage(message);
		ad.setButton("OK", new DialogInterface.OnClickListener() {  
		    public void onClick(DialogInterface dialog, int which) {  
		        dialog.dismiss();                      
		    }  
		});  
		ad.show();
	}

	/**
<<<<<<< .mine
	 * makes sure the time is not empty field
=======
	 * make sure the time is not empty field
>>>>>>> .r15
	 * @param string
	 * @return
	 */
	private Integer parsetime(String string) {
		if (string.length() == 0) {
			return 0;
			
		} else {
			return Integer.parseInt(string);
		}
		
	}

	
}
